﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.Threading;

namespace FileChat
{
    public partial class MainForm : Form
    {
        public String FileChatPath;//配置文件位置
        public String FileChatBasePath;
        public List<User> UserList = new List<User>();
        public User CurrentUser = new User();
        private Dictionary<string, ChatForm> chatFormDic = new Dictionary<string, ChatForm>();
        public delegate void ShowChatForm(FileChatMessage msg);

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            try {
                FormLogin frm = new FormLogin();
                frm.MyMainForm = this;
                if (frm.ShowDialog() != DialogResult.OK) {
                    this.Close();
                    this.Dispose();
                }
                LoadUserList();
                //Todo:检测信息
                FileSystemWatcher userListWatcher = new FileSystemWatcher();
                string userListWatcherFile = string.Format("{0}\\FileChatData.xml",FileChatBasePath);

                //向目标用户的文件夹里写一个xml聊天信息 或二进制聊天信息流
                string targetFilePath = string.Format(String.Format("{0}\\ChatData\\{1}\\rcvd", FileChatBasePath, CurrentUser.ID));
                if (!Directory.Exists(targetFilePath))
                {
                    Directory.CreateDirectory(targetFilePath);
                }

                //读取离线消息
               String[] offlineMsgList= Directory.GetFiles(targetFilePath);
               foreach (string offlineMsg in offlineMsgList) {
                   //Console.WriteLine(offlineMsg);
                   DisplayChatFrom(offlineMsg);
               }
                


                //检测信息
                FileSystemWatcher watcher = new FileSystemWatcher(); 
                watcher.Path = targetFilePath;
                watcher.Changed += new FileSystemEventHandler(watcher_Changed);

                // Begin watching.
                watcher.EnableRaisingEvents = true;

                

            }catch(Exception ex){
                MessageBox.Show(ex.Message);
            }
           
        }

        void watcher_Created(object sender, FileSystemEventArgs e)
        {
            MessageBox.Show("u have a new msg ! a new file created");

        }

        void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            try
            {
                DisplayChatFrom(e.FullPath);
            }
            catch (Exception ex)
            { 
            
            
            }
        }

        private void DisplayChatFrom(string msgFullPath) {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(msgFullPath);
            XmlNode root = xmlDoc.SelectSingleNode("FileChat/Message");
            FileChatMessage msg = new FileChatMessage();
            msg.Time = root.SelectSingleNode("Time").InnerText;
            msg.Content = root.SelectSingleNode("Content").InnerText;
            msg.Sender = new User();
            XmlNode xn = root.SelectSingleNode("User");
            foreach (PropertyInfo pi in msg.Sender.GetType().GetProperties())
            {
                foreach (XmlAttribute xa in xn.Attributes)
                {
                    if (xa.Name == pi.Name)
                    {
                        pi.SetValue(msg.Sender, xn.Attributes[pi.Name].Value, null);
                        break;
                    }
                }
            }
            ShowChatForm chatfrm = new ShowChatForm(showChatForm);
            this.Invoke(chatfrm, new object[] { msg });
            FileInfo fi = new FileInfo(msgFullPath);
            string targetFilePath = string.Format(String.Format("{0}\\ChatData\\{1}\\history", FileChatBasePath, CurrentUser.ID));
            string targetFileFullPath = string.Format(String.Format("{0}\\ChatData\\{1}\\history\\{2}", FileChatBasePath, CurrentUser.ID, fi.Name));
            if (!Directory.Exists(targetFilePath))
            {
                Directory.CreateDirectory(targetFilePath);
            }
            File.Move(msgFullPath, targetFileFullPath);    
        }

        private void showChatForm(FileChatMessage msg) {
            ChatForm frm = GetChatForm(msg.Sender);
            if (frm.IsDisposed) {
                RemoveChatForm(msg.Sender);
                frm = GetChatForm(msg.Sender);
            }      
            frm.Show();
            frm.TopMost = true;
            frm.Focus();
            frm.ShowMessage(msg);
        }

        private void AddChatForm(string userID, ChatForm frm) {
            if (!chatFormDic.ContainsKey(userID)) {
                chatFormDic.Add(userID, frm);
            } 
        }

        private void RemoveChatForm(User u) {
            if (chatFormDic.ContainsKey(u.ID.ToString()))
            {
                chatFormDic.Remove(u.ID.ToString());
            }
        }

        private ChatForm GetChatForm(User u) { 
            if(chatFormDic.ContainsKey(u.ID.ToString()))
            {
                return chatFormDic[u.ID.ToString()];
            }
            else
            {
                ChatForm frm = new ChatForm();
                frm.User = u;
                frm.Text = string.Format(u.DisplayName);
                frm.CurrentUser = CurrentUser;
                frm.FileChatBasePath = FileChatBasePath;
                frm.Show();
                AddChatForm(u.ID.ToString(), frm);
                return frm;
            }
        }

        private void LoadUserList() {
            try
            {
                treeView1.Nodes.Clear();
                //显示用户列表
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(FileChatPath);
                XmlNode root = xmlDoc.SelectSingleNode("FileChat/UserList");
                UserList = Util.GetUserList(root);

                foreach (User user in UserList)
                {
                    if (user.ID != CurrentUser.ID)
                    {
                        TreeNode tn = new TreeNode(user.DisplayName);
                        tn.Tag = user;
                        treeView1.Nodes.Add(tn);
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("哈哈，这个功能还没有做，请重新打开一下软件即更新了联系人清单！");
        }

        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (treeView1.SelectedNode == null) { return; }
            User user = treeView1.SelectedNode.Tag as User;
            //一个用户一个聊天窗口，不需要反复打开
            ChatForm frm = GetChatForm(user);
            if (frm.IsDisposed)
            {
                RemoveChatForm(user);
                frm = GetChatForm(user);
            }
            frm.Show();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }

        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            this.Show();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
